/*
 * @brief :   
 * @date :  2021-11-xx
 * @version : v1.0.0
 * @copyright(c) 2020 : OptoMedic company Co.,Ltd. All rights reserved
 * @Change Logs:   
 * @date         author         notes:  
 */
#include "led.h"
#include <stdio.h> 
#include <stdlib.h> 
#include <sys/types.h> 
#include <sys/stat.h> 
#include <fcntl.h> 
#include <unistd.h> 
#include <string.h> 

#ifndef ARR_COUNTOF
#define ARR_COUNTOF(a)   (sizeof(a) / sizeof(a[0]))
#endif

/* 常见触发方式 */
#define TRIGGER_NONE     "none"    /* 无触发方式 */
#define TRIGGER_DISK_ACTIVITY   "disk-activity"   /* 硬盘活动 */
#define TRIGGER_NAND_DISK       "nand-disk"  /* nand flash活动 */
#define TRIGGER_MTD  "mtd"      /* mtd设备活动 */
#define TRIGGER_TIMER   "timer"      /* 定时器 */
#define TRIGGER_HEARTBEAT "heartbeat" /* 系统心跳 */

int led_set_trigger(char *ledname, led_trig_t trig)
{
    int fd;
    char path[256] = {0};
    sprintf(path, "/sys/class/leds/%s/trigger", ledname);
    fd = open(path, O_RDWR); 
    if (fd < 0) return -1;

    char trigger_style[6][30] = {{TRIGGER_NONE}, {TRIGGER_DISK_ACTIVITY}, {TRIGGER_NAND_DISK}, 
                                {TRIGGER_MTD}, {TRIGGER_TIMER}, {TRIGGER_HEARTBEAT}};
    led_trig_t trigger_index[6] = {LED_TRIG_NONE, LED_TRIG_DISK_ACTIVE, LED_TRIG_NAND_DISK, 
                                   LED_TRIG_MTD, LED_TRIG_TIMER, LED_TRIG_HEARTBEAT};
    char trigger[20] = {0};
    for (int i = 0; i < ARR_COUNTOF(trigger_index); i++) 
    {
        if (trig == trigger_index[i])
        {
            sprintf(trigger, "%s", trigger_style[i]);
            break;
        }
    }

    int len = strlen(trigger);
    if (len != write(fd, trigger, len)) return -1;

    return 0;
}   

int led_set_brightness(char *ledname, int brightness)
{
    int fd;
    char path[256] = {0};
    sprintf(path, "/sys/class/leds/%s/brightness", ledname);
    fd = open(path, O_RDWR); 
    if (fd < 0) return -1;

    char brights[10] = {0};
    sprintf(brights, "%d", brightness);
    int len = strlen(brights);
    if (len != write(fd, brights, len)) return -1;

    return 0;
}

int led_get_max_brightness(char *ledname)
{
    int fd;
    int max_brightness;
    char brights[20] = {0};
    char path[256] = {0};
    sprintf(path, "/sys/class/leds/%s/max_brightness", ledname);
    fd = open(path, O_RDONLY); 
    if (fd < 0) return -1;

    read(fd, brights, sizeof(brights));
    max_brightness = atoi(brights);
    return max_brightness;
}

